/*
 * 
 *
 *
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.dao.VerificationCodeDao;
import com.hboxs.asl.entity.VerificationCode;
import org.springframework.stereotype.Repository;

import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;

/**
 * Dao - 邮箱验证码
 */
@Repository("verificationCodeDaoImpl")
public class VerificationCodeDaoImpl extends BaseDaoImpl<VerificationCode, Long> implements VerificationCodeDao {

    /**
     * 判断用户手机是否存在
     * @param phone 用户手机(忽略大小写)
     * @return 用户名是否存在
     */
    public boolean phoneExists(String phone){
        if (phone == null) {
            return false;
        }
        String jpql = "select count(*) from VerificationCode verificationCode where verificationCode.phone = :phone";
        Long count = entityManager.createQuery(jpql, Long.class).setFlushMode(FlushModeType.COMMIT).setParameter("phone", phone).getSingleResult();
        return count > 0;
    }

    /**
     * 根据用户手机判断用户是否申请验证码记录,
     * @param phone 用户手机
     * @return VerificationCode独享
     */
    public VerificationCode findByPhone(String phone){
        if (phone == null) {
            return null;
        }
        try {
            String jpql = "select verificationCode from VerificationCode verificationCode where verificationCode.phone = :phone";
            return entityManager.createQuery(jpql, VerificationCode.class).setFlushMode(FlushModeType.COMMIT).setParameter("phone", phone).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

}
